<template>
  <div class="home">
    <!-- 轮播图 -->
    <el-carousel height="500px" class="banner" indicator-position="outside">
      <el-carousel-item v-for="item in banners" :key="item.id">
        <div class="banner-content" :style="{ backgroundImage: `url(${item.image})` }">
          <div class="banner-text">
            <h2>{{ item.title }}</h2>
            <p>{{ item.description }}</p>
            <el-button type="primary" size="large" @click="handleBannerClick(item.route)">
              立即预约
            </el-button>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 服务特点 -->
    <div class="features section">
      <h2 class="section-title">我们的服务</h2>
      <el-row :gutter="30">
        <el-col :span="6" v-for="feature in features" :key="feature.id">
          <div
            class="feature-item"
            @click="feature.route && handleFeatureClick(feature)"
            :class="{ clickable: feature.route }"
          >
            <el-icon :size="50" :color="feature.color">
              <component :is="feature.icon" />
            </el-icon>
            <h3>{{ feature.title }}</h3>
            <p>{{ feature.description }}</p>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 医院列表 -->
    <div class="hospitals section">
      <div class="section-header">
        <h2 class="section-title">合作医院</h2>
        <el-button type="primary" text>查看更多</el-button>
      </div>
      <el-row :gutter="30">
        <el-col :span="8" v-for="hospital in hospitals" :key="hospital.id">
          <el-card class="hospital-card" :body-style="{ padding: '0px' }">
            <div class="hospital-image">
              <img :src="hospital.image" :alt="hospital.name">
              <div class="hospital-level">{{ hospital.level }}</div>
            </div>
            <div class="hospital-info">
              <h3>{{ hospital.name }}</h3>
              <p class="hospital-address">
                <el-icon><Location /></el-icon>
                {{ hospital.address }}
              </p>
              <p class="hospital-description">{{ hospital.description }}</p>
              <div class="hospital-departments">
                <el-tag v-for="dept in (hospital.departments || []).slice(0,4)"
                  :key="dept" size="small" effect="plain">
                  {{ dept }}
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 优秀陪护师 -->
    <div class="escorts-section">
      <div class="section-header">
        <h2 class="section-title">优秀陪诊师</h2>
        <el-button type="primary" text @click="goToAppointment">预约陪护</el-button>
        <!-- 添加更多内容按钮 -->
        <el-button type="primary" text @click="showAllEscorts = true">更多内容</el-button>
      </div>
      <el-row :gutter="30">
        <!-- 只展示前 4 个陪护师 -->
        <el-col :span="6" v-for="escort in escorts.slice(0, 4)" :key="escort.id">
          <el-card class="escort-card" shadow="hover">
            <div class="escort-avatar">
              <el-avatar :size="120" :src="escort.avatar"></el-avatar>
              <div class="escort-status" :class="{ available: escort.is_available }">
                {{ escort.is_available ? '可预约' : '已约满' }}
              </div>
            </div>
            <div class="escort-info">
              <h3>{{ escort.name }}</h3>
              <p class="escort-title">
                {{ escort.gender }} | {{ escort.age }}岁 | {{ escort.experience }}年经验
              </p>
              <div class="escort-rating">
                <el-rate v-model="escort.rating" disabled></el-rate>
                <span class="rating-text">{{ escort.rating }}分</span>
              </div>
              <p class="escort-intro">
                {{ escort.introduction }}
              </p>
              <div class="escort-price">
                <span class="price">¥{{ escort.price.toFixed(2) }}</span>/小时
              </div>
              <el-button type="primary" @click="goToAppointment">立即预约</el-button>
            </div>
            <el-button type="text" @click="handleLearnMore(escort)" class="learn-more-btn">
              了解更多
            </el-button>
          </el-card>
        </el-col>
      </el-row>

      <!-- 单个陪护师详细信息弹窗 -->
      <el-dialog v-model="dialogVisible" title="陪护师详细信息" width="50%">
        <div v-if="selectedEscort" class="escort-detail">
          <el-avatar :size="120" :src="selectedEscort.avatar"></el-avatar>
          <h3>{{ selectedEscort.name }}</h3>
          <p>
            {{ selectedEscort.gender }} | {{ selectedEscort.age }}岁 | {{ selectedEscort.experience }}年经验
          </p>
          <el-rate v-model="selectedEscort.rating" disabled></el-rate>
          <div class="detailed-intro">
            {{ selectedEscort.detailedIntroduction }}
          </div>
          <p>价格: ¥{{ selectedEscort.price.toFixed(2) }}/小时</p>
          <p>状态: {{ selectedEscort.is_available ? '可预约' : '已约满' }}</p>
        </div>
        <div v-else>
          <p>未选择陪护师</p>
        </div>
      </el-dialog>

      <!-- 所有陪护师信息弹窗 -->
      <el-dialog v-model="showAllEscorts" title="所有陪护师信息" width="80%">
        <el-row :gutter="30">
          <el-col :span="6" v-for="escort in escorts" :key="escort.id">
            <el-card class="escort-card" shadow="hover">
              <div class="escort-avatar">
                <el-avatar :size="120" :src="escort.avatar"></el-avatar>
                <div class="escort-status" :class="{ available: escort.is_available }">
                  {{ escort.is_available ? '可预约' : '已约满' }}
                </div>
              </div>
              <div class="escort-info">
                <h3>{{ escort.name }}</h3>
                <p class="escort-title">
                  {{ escort.gender }} | {{ escort.age }}岁 | {{ escort.experience }}年经验
                </p>
                <div class="escort-rating">
                  <el-rate v-model="escort.rating" disabled></el-rate>
                  <span class="rating-text">{{ escort.rating }}分</span>
                </div>
                <p class="escort-intro">
                  {{ escort.introduction }}
                </p>
                <div class="escort-price">
                  <span class="price">¥{{ escort.price.toFixed(2) }}</span>/小时
                </div>
                <el-button type="primary" @click="goToAppointment">立即预约</el-button>
              </div>
              <el-button type="text" @click="handleLearnMore(escort)" class="learn-more-btn">
                了解更多
              </el-button>
            </el-card>
          </el-col>
        </el-row>
      </el-dialog>
    </div>

    <!-- 健康小贴士 -->
    <div class="health-tips section">
      <div class="section-header">
        <h2 class="section-title">健康小贴士</h2>
        <el-button type="primary" text>更多内容</el-button>
      </div>
      <el-row :gutter="30">
        <el-col :span="8" v-for="tip in healthTips" :key="tip.id">
          <el-card class="tip-card" shadow="hover">
            <div class="tip-image">
              <img :src="tip.image" :alt="tip.title">
            </div>
            <div class="tip-content">
              <h3>{{ tip.title }}</h3>
              <p>{{ tip.content }}</p>
              <div class="tip-footer">
                <span class="date">{{ tip.date }}</span>
                <!--<el-button type="primary" link>阅读更多</el-button>-->
                <!-- ===== -->
                <el-button type="primary" link @click="handleTipClick(tip)">阅读更多</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 服务流程 -->
    <div class="process section">
      <h2 class="section-title">服务流程</h2>
      <el-steps :active="4" finish-status="success" align-center>
        <el-step title="在线预约" description="选择合适的陪护师">
          <template #icon>
            <el-icon><Calendar /></el-icon>
          </template>
        </el-step>
        <el-step title="确认订单" description="填写就医信息">
          <template #icon>
            <el-icon><Document /></el-icon>
          </template>
        </el-step>
        <el-step title="支付订单" description="在线完成支付">
          <template #icon>
            <el-icon><Wallet /></el-icon>
          </template>
        </el-step>
        <el-step title="开始服务" description="专业陪护服务">
          <template #icon>
            <el-icon><Service /></el-icon>
          </template>
        </el-step>
      </el-steps>
    </div>

    <el-dialog
      v-model="tipDialogVisible"
      :title="currentTip?.title"
      width="50%"
      :before-close="() => tipDialogVisible = false"
    >
      <div class="tip-dialog-content">
        <img :src="currentTip?.image" :alt="currentTip?.title" class="tip-dialog-image">
        <p class="tip-dialog-text">{{ currentTip?.content }}</p>
        <div class="tip-dialog-footer">
          <span class="date">发布时间：{{ currentTip?.date }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { getHospitalList } from '@/api/hospital'
import { getEscortList } from '@/api/escort'
import { departments } from '@/constants/departments'
import { ElMessage } from 'element-plus'
import {
  Location,
  Calendar,
  Document,
  Wallet,
  User,
  Monitor,
  Service,
  CircleCheck
} from '@element-plus/icons-vue'
import { handleError } from '@/utils/error'
import axios from 'axios'
import {ip} from '../router/ip.js'

const router = useRouter()

const hospitals = ref([
  {
    id: 1,
    name: '北京协和医院',
    level: '三级甲等',
    address: '北京市东城区帅府园1号',
    description: '中国最著名的医院之一，拥有百年历史...',
    image: 'https://picsum.photos/400/300?random=1',
    departments: ['内科', '外科', '妇产科', '儿科', '骨科']
  },
  {
    id: 2,
    name: '北京大学第一医院',
    level: '三级甲等',
    address: '北京市西城区西什库大街8号',
    description: '集医疗、教学、科研为一体的综合性医院...',
    image: 'https://picsum.photos/400/300?random=2',
    departments: ['内科', '外科', '神经科', '心血管科']
  }
])

// 陪护师数据
const escorts = ref([])

// 弹窗控制
const dialogVisible = ref(false);
const selectedEscort = ref(null);

// 所有陪护师信息弹窗控制
const showAllEscorts = ref(false);

// 点击"了解更多"按钮
const handleLearnMore = (escort) => {
  // 打印原始数据
  console.log('原始数据:', escort);
  
  // 直接赋值，不使用展开运算符
  selectedEscort.value = escort;
  
  // 打印赋值后的数据
  console.log('赋值后的数据:', selectedEscort.value);
  
  // 确认数据字段
  console.log('详细介绍是否存在:', selectedEscort.value?.detailedIntroduction ? '是' : '否');
  
  dialogVisible.value = true;
};

// 定义轮播图数据，包含路由信息
const banners = ref([
  {
    id: 1,
    title: '智能导诊',
    description: '快速找到合适的科室',
    image: 'https://img.freepik.com/free-photo/medical-banner-with-doctor-wearing-coat_23-2149611193.jpg',
    route: '/smart-guide'
  },
  {
    id: 2,
    title: '智能问诊',
    description: '在线咨询医生',
    image: 'https://img.freepik.com/free-photo/doctor-with-stethoscope-hands-hospital-background_1423-1.jpg',
    route: '/ai-chat'
  },
  {
    id: 3,
    title: '陪诊预约',
    description: '预约专业陪护师',
    image: 'https://img.freepik.com/free-photo/medical-banner-with-doctor-wearing-coat_23-2149611193.jpg',
    route: '/appointments'
  }
])

// 健康小贴士数据
const healthTips = ref([
  {
    id: 1,
    title: '日常防护指南',
    content: '在日常生活中，做好个人防护是远离疾病困扰的关键。首先，保持良好的个人卫生习惯至关重要。勤洗手是预防疾病传播的有效方法，尤其是在接触公共设施或外出回家后，应使用肥皂或洗手液，用流动水洗手至少 20 秒。\n同时，尽量避免用手触摸眼睛、鼻子和嘴巴，以减少病毒通过黏膜感染的风险。\n咳嗽或打喷嚏时，应用纸巾或肘部遮挡口鼻，避免直接用手。',
    image: 'https://picsum.photos/400/300?random=3',
    date: '2024-02-20',
    route: '/health-tips/1'
  },
  {
    id: 2,
    title: '合理膳食建议',
    content: '科学饮食是健康生活的基础。首先，保持饮食均衡，每天摄入多样化的食物，包括谷类、蔬菜、水果、肉类、蛋类、奶类和豆类，确保身体获得全面的营养。\n控制食物摄入量，避免过量饮食，减少高糖、高脂肪和高盐食物的摄入，以预防肥胖和慢性疾病。多喝水，每天建议饮用 1500-2000 毫升水，帮助身体代谢和排毒。\n定时进餐，规律吃三餐，早餐要营养丰富，午餐和晚餐以清淡为主。选择健康的烹饪方式，如蒸、煮、炖，减少油炸和烧烤。',
    image: 'https://picsum.photos/400/300?random=4',
    date: '2024-02-19',
    route: '/health-tips/2'
  },
  {
    id: 3,
    title: '运动健身指导',
    content: '适量运动是保持健康的重要方式。每天进行 30 分钟的中等强度运动，如快走、慢跑、骑车或瑜伽，可以有效增强体质，提高免疫力。\n运动不仅能改善心肺功能，还能帮助控制体重，缓解压力，提升情绪。选择适合自己的运动项目很重要。初学者可以从低强度运动开始，如散步或拉伸，逐渐增加强度和时间。\n对于有运动基础的人，可以尝试跑步、游泳或力量训练，以进一步提升体能。运动前后要注意热身和放松，避免受伤。\n保持规律的运动习惯，每周至少锻炼 3-5 次，才能达到最佳效果。同时，结合健康饮食和充足睡眠，让身体更健康、更有活力。',
    image: 'https://picsum.photos/400/300?random=5',
    date: '2024-02-18',
    route: '/health-tips/3'
  }
])

// 服务特点数据
const features = ref([
  {
    id: 1,
    title: '专业陪诊',
    description: '经验丰富的医疗陪诊团队',
    icon: User,
    color: '#409EFF',
    route: '/appointments'
  },
  {
    id: 2,
    title: '智能导诊',
    description: 'AI辅助诊断，精准推荐科室',
    icon: Monitor,
    color: '#67C23A',
    route: '/smart-guide'
  },
  {
    id: 3,
    title: '智能问诊',
    description: '在线咨询，智能解答健康问题',
    icon: Service,
    color: '#67C23A',
    route: '/ai-chat'
  },
  {
    id: 4,
    title: '关于我们',
    description: '了解更多关于我们平台的信息',
    icon: CircleCheck,
    color: '#F56C6C',
    route: '/about-us'
  }
])

// 添加以下数据
const tipDialogVisible = ref(false)
const currentTip = ref(null)

// 获取医院列表
// const fetchHospitals = async () => {
//   try {
//     const data = await getHospitalList()
//     if (data && data.length) {
//       hospitals.value = data.map(hospital => ({
//         ...hospital,
//         departments: hospital.departments || []
//       }))
//     }
//   } catch (error) {
//   }
// }

// 获取陪护师列表
const fetchEscorts = async () => {
    const response = await axios.get(`http://${ip}:8000/api/getAllCaregivers`);
    escorts.value = response.data.map(e => {
      if (typeof e === 'object' && e !== null) {
        return {
          ...e,
          price: parseFloat(e.money),
          is_available: e.status === 'available'
        };
      }
      return e;
    });
};

onMounted(() => {
  // fetchHospitals()
  fetchEscorts()
})

const goToAppointment = () => {
  const token = localStorage.getItem('token')
  const role = localStorage.getItem('role')
  
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  if (role !== 'user') {
    ElMessage.warning('只有用户才能预约陪诊')
    return
  }
  
  router.push('/appointments')
}

const getHospitalName = (id) => {
  const hospital = hospitals.value.find(h => h.id === id)
  return hospital ? hospital.name : ''
}

const getDepartmentName = (id) => {
  const department = departments.find(d => d.id === id)
  return department ? department.name : ''
}

const handleFeatureClick = (feature) => {
  if (!feature.route) return
  
  const token = localStorage.getItem('token')
  const role = localStorage.getItem('role')
  
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  if (role !== 'user') {
    ElMessage.warning('只有用户才能访问此功能')
    return
  }
  
  router.push(feature.route)
}
// 处理轮播图点击事件
const handleBannerClick = (route) => {
  router.push(route)
}

const handleTipClick = (tip) => {
  currentTip.value = tip
  tipDialogVisible.value = true
}
</script>

<style scoped lang="scss">
.home {
  .banner {
    margin-bottom: 60px;
    
    .banner-content {
      height: 100%;
      background-size: cover;
      background-position: center;
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.3);
      }
      
      .banner-text {
        position: absolute;
        left: 10%;
        top: 50%;
        transform: translateY(-50%);
        color: #fff;
        max-width: 500px;
        
        h2 {
          font-size: 36px;
          margin-bottom: 20px;
        }
        
        p {
          font-size: 18px;
          margin-bottom: 30px;
        }
      }
    }
  }
  
  .section {
    margin-bottom: 60px;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;
    }
    
    .section-title {
      font-size: 28px;
      color: #303133;
      margin-bottom: 30px;
      text-align: center;
      
      &::after {
        content: '';
        display: block;
        width: 50px;
        height: 3px;
        background: #409EFF;
        margin: 15px auto 0;
      }
    }
  }
  
  .features {
    .feature-item {
      &.clickable {
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
      }
      
      padding: 20px;
      text-align: center;
      border-radius: 8px;
      
      h3 {
        margin: 15px 0 10px;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #606266;
      }
    }
  }
  
  .hospital-card {
    margin-bottom: 30px;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 16px rgba(0,0,0,0.1);
    }
    
    .hospital-image {
      position: relative;
      height: 200px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .hospital-level {
        position: absolute;
        right: 10px;
        top: 10px;
        background: rgba(103,194,58,0.9);
        color: #fff;
        padding: 4px 8px;
        border-radius: 4px;
      }
    }
    
    .hospital-info {
      padding: 20px;
      
      h3 {
        margin: 0 0 10px;
        font-size: 18px;
      }
      
      .hospital-address {
        color: #909399;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        gap: 5px;
      }
      
      .hospital-description {
        color: #606266;
        margin-bottom: 15px;
        height: 40px;
        overflow: hidden;
      }
      
      .hospital-departments {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
      }
    }
  }
  
  .escort-card {
  position: relative; /* 确保子元素的定位基于此容器 */
}

.learn-more-btn {
   position: absolute; /* 绝对定位 */
   top: 10px; /* 距离顶部10px */
   right: 10px; /* 距离右侧10px，改left为right */
   z-index: 10; /* 确保按钮在最上层 */
   background-color: rgba(255, 255, 255, 0.9); /* 半透明背景 */
   border: 1px solid #ccc; /* 边框 */
   padding: 5px 10px; /* 内边距 */
   border-radius: 4px; /* 圆角 */
   cursor: pointer; /* 鼠标指针 */
   font-size: 14px; /* 字体大小 */
   color: #409eff; /* 字体颜色 */
}

.learn-more-btn:hover {
  background-color: rgba(255, 255, 255, 1); /* 鼠标悬停时背景变不透明 */
  color: #66b1ff; /* 鼠标悬停时字体颜色 */
}
.escort-avatar {
  text-align: center;
  margin-bottom: 15px;
  position: relative;
}



.escort-status {
   font-size: 10px; /* 字体大小 */
   padding: 2px 6px; /* 内边距 */
   border-radius: 8px; /* 圆角 */
   background-color: rgba(240, 240, 240, 0.8);
   color: #333; /* 默认文字颜色 */
   display: inline-block; /* 让按钮与姓名在同一行显示 */
   margin-left: 10px; /* 调整按钮与姓名的间距 */
   white-space: nowrap; /* 防止文字换行 */
   vertical-align: middle; /* 垂直对齐 */
}

.escort-status.available {
   background-color: #67c23a; /* 可预约状态背景颜色 */
   color: #fff; /* 可预约状态文字颜色 */
}

.escort-status:not(.available) {
   background-color: #f56c6c; /* 已约满状态背景颜色 */
   color: #fff; /* 已约满状态文字颜色 */
}
    
.escort-info {
   text-align: center;
      
   h3 {
     margin: 0;
     font-size: 18px;
   }
      
   .escort-title {
     color: #909399;
     margin: 10px 0;
   }
      
   .escort-rating {
      margin: 10px 0;
        
      .rating-text {
        margin-left: 10px;
        color: #f7ba2a;
      }
   }
      
    .escort-intro {
      color: #606266;
      margin: 15px 0;
      height: 40px;
      overflow: hidden;
    }
      
    .escort-price {
      margin: 15px 0;
        
      .price {
        font-size: 24px;
        color: #f56c6c;
        font-weight: bold;
      }
    }
  }

  
  .tip-card {
    margin-bottom: 30px;
    
    .tip-image {
      height: 200px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .tip-content {
      padding: 20px;
      
      h3 {
        margin: 0 0 10px;
        font-size: 18px;
      }
      
      p {
        color: #606266;
        margin-bottom: 15px;
        height: 40px;
        overflow: hidden;
      }
      
      .tip-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .date {
          color: #909399;
        }
      }
    }
  }
  
  .process {
    padding: 60px 0;
    background: #f5f7fa;
    margin: -60px -20px 0;
    
    .el-steps {
      max-width: 1000px;
      margin: 0 auto;
    }
  }

  .tip-dialog-content {
    .tip-dialog-image {
      width: 100%;
      max-height: 300px;
      object-fit: cover;
      border-radius: 8px;
      margin-bottom: 20px;
    }

    .tip-dialog-text {
      font-size: 16px;
      line-height: 1.8;
      color: #606266;
      margin-bottom: 20px;
      white-space: pre-line;  // 保留换行符
    }

    .tip-dialog-footer {
      text-align: right;
      color: #909399;
      font-size: 14px;
    }
  }

  .escort-detail {
    text-align: center;
    padding: 20px;
    
    .el-avatar {
      margin-bottom: 15px;
    }
    
    h3 {
      margin: 10px 0;
      font-size: 20px;
      color: #303133;
    }
    
    .detailed-intro {
      text-align: left;
      white-space: pre-wrap !important;
      line-height: 1.6;
      color: #606266;
      margin: 15px 0;
      padding: 15px;
      background: #f5f7fa;
      border-radius: 4px;
      max-height: 400px;
      overflow-y: auto;
    }
    
    .el-rate {
      margin: 10px 0;
    }
  }
}
</style> 